from base64 import encode
import os
import datetime
import hashlib
import wget
import string
import random
from sqlite3 import Cursor
from mysql.connector import connect, Error

class Database:
    def __init__(self, host, user, password) -> None:
        self.connection = connect(host=host, user=user, password=password)
        self.cursor = self.connection.cursor()

    def getSchedule(self, day_given):
        if day_given == 'today':
            d = datetime.date.today()
            weekday = d.weekday()
        elif day_given == 'tomorrow':
            d = datetime.date.today() + datetime.timedelta(days=1)
            weekday = d.weekday()
        else:
            d = datetime.date.today()
            if int(day_given) > d.weekday():
                weekday = int(day_given)
            else:
                weekday = int(day_given)
                d += datetime.timedelta(weeks=1)

        if weekday == 0:
            day = 'monday'
        elif weekday == 1:
            day = 'tuesday'
        elif weekday == 2:
            day = 'wednesday'
        elif weekday == 3:
            day = 'thursday'
        elif weekday == 4:
            day = 'friday'
        elif weekday == 5:
            day = 'weekend'
        elif weekday == 6:
            day = 'weekend'
        if day == 'weekend':
            return 'Сегодня выходной!'
        if (d.isocalendar().week % 2 == 0):
            parity = 'even'
        else:
            parity = 'odd'
        self.cursor.execute('USE schedule;')
        self.cursor.execute(f'SELECT subject,type,cabinet,time FROM {day} LEFT JOIN cabinets ON {day}.id_cabinet_{parity}=cabinets.id NATURAL LEFT JOIN time LEFT JOIN subjects ON {day}.id_{parity} = subjects.id LEFT JOIN types ON {day}.id_type_{parity}=types.id;')
        res = self.cursor.fetchall()      
        return res

    def check(self):
        with open('schedule.pdf', 'rb') as file:
            data = file.read()
            md5_ethalon = hashlib.md5(data).hexdigest()
        letters = string.ascii_lowercase
        rand_string = ''.join(random.choice(letters) for i in range(8))
        rand_string = rand_string + '.pdf'
        wget.download('https://mgsu.ru/student/Raspisanie_zanyatii_i_ekzamenov/fayly-raspisaniya-dlya-skachivaniya/IZ_2_b.pdf', rand_string)
        with open(rand_string, 'rb') as file:
                data = file.read()
                md5_new = hashlib.md5(data).hexdigest()
        os.remove(rand_string)
        if md5_ethalon == md5_new:
            return True
        else:
            return False
